from django.db.models import Count
from django.shortcuts import render, redirect
from . import models
from . import forms

# Create your views here.

# 主页视图
from home.models import CountItem, New, Disscuss, ContentItem, Tip


def index(request):
    count_item = CountItem.objects.get(count_key='home')
    count_item.editor_num = models.User.objects.filter(is_contribute='yes').count()
    count_item.save()
    content_num = models.ContentItem.objects.all().count()
    content_item = models.ContentItem.objects.all()
    new_list = New.objects.order_by('-new_date')[:5]
    # editor_list = models.ContentItem.objects.order_by('item_editor_id').distinct('item_editor_id')
    editor_list = models.User.objects.filter(is_contribute="yes")
    discuss_list = Disscuss.objects.order_by('-discuss_date')[:5]
    latest_history = models.ActionHistory.objects.order_by('-action_date')[:5]
    tip_list = Tip.objects.all()
    login_form = forms.UserForm()
    news_form = forms.NewsForm()
    tip_form = forms.TipForm()
    # if request.session.get('is_login', None):
    # return redirect('/home/')
    if request.method == 'POST':
        login_form = forms.UserForm(request.POST)
        news_form = forms.NewsForm(request.POST)
        tip_form = forms.TipForm(request.POST)
        if login_form.is_valid():
            # 验证数据:密码长度
            username = login_form.cleaned_data.get('username')
            password = login_form.cleaned_data.get('password')
            try:
                user = models.User.objects.get(user_id=username)
            except:
                message = '用户名不存在'
                return render(request, 'home/home.html', locals())
            if user.user_psw == password:
                request.session['is_login'] = True
                request.session['user_id'] = user.user_id
                # return redirect('/home/')
            else:
                message = "密码不正确"
                return render(request, 'home/home.html', locals())
        elif news_form.is_valid():
            news_title = news_form.cleaned_data.get('new_title')
            news_content = news_form.cleaned_data.get('new_content')
            new_news = models.New()
            new_news.new_title = news_title
            new_news.new_content = news_content
            new_news.save()
        elif tip_form.is_valid():
            tip_content = tip_form.cleaned_data.get('tip_content')
            new_tip = models.Tip()
            new_tip.tip_content = tip_content
            new_tip.save()
        else:
            return render(request, 'home/home.html', locals())

    return render(request, 'home/home.html', locals())


# logout
def logout(request):
    if not request.session.get('is_login', None):
        return redirect("/index/")
    request.session.flush()
    return render(request, 'home/logout.html')


# register_success
def register_success(request):
    return render(request, 'home/register_success.html')


# register
def register(request):
    content_num = models.ContentItem.objects.all().count()
    count_item = CountItem.objects.get(count_key='home')
    editor_list = models.User.objects.filter(is_contribute="yes")
    if request.session.get('is_login', None):
        return redirect('/home/')
    register_form = forms.RegisterForm()
    if request.method == 'POST':
        register_form = forms.RegisterForm(request.POST)
        message = '请检查填写的内容'
        if register_form.is_valid():
            username = register_form.cleaned_data.get('username')
            real_name = register_form.cleaned_data.get('real_name')
            password = register_form.cleaned_data.get('password')
            password_confirm = register_form.cleaned_data.get('password_confirm')
            email = register_form.cleaned_data.get('email')

            if password_confirm != password:
                message = '两次输入的密码不一致!'
                return render(request, 'home/register.html', locals())
            else:
                same_username = models.User.objects.filter(user_id=username)
                if same_username:
                    message = '用户名已存在'
                    return render(request, 'home/register.html', locals())
                same_email = models.User.objects.filter(user_email=email)
                if same_email:
                    message = '该邮箱地址已被注册'
                    return render(request, 'home/register.html', locals())

                new_user = models.User()
                new_user.user_id = username
                new_user.user_psw = password
                new_user.user_email = email
                new_user.user_real_name = real_name
                new_user.save()
                return redirect('/register_success/')

        else:
            return render(request, 'home/register.html', locals())
    return render(request, 'home/register.html', locals())


def user_central(request):
    content_num = models.ContentItem.objects.all().count()
    count_item = CountItem.objects.get(count_key='home')
    editor_list = models.User.objects.filter(is_contribute="yes")
    user_info = models.User.objects.get(user_id=request.session['user_id'])
    if not request.session.get('is_login', None):
        return redirect('/home/')
    user_central_form = forms.UserCentralForm()
    if request.method == 'POST':
        user_central_form = forms.UserCentralForm(request.POST)

        if user_central_form.is_valid():
            # 修改密码表单
            old_psw = user_central_form.cleaned_data.get('old_psw')
            new_psw = user_central_form.cleaned_data.get('new_psw')
            new_psw_confirm = user_central_form.cleaned_data.get('new_psw_confirm')

            # 设置姓名表单
            real_name = user_central_form.cleaned_data.get('real_name')
            # 修改密码功能
            if old_psw:
                if new_psw != new_psw_confirm:
                    message_warn = '两次输入密码不一致'
                    return render(request, 'home/user_central.html', locals())
                else:
                    if old_psw != models.User.objects.get(user_id=request.session.get('user_id', None)).user_psw:
                        message_warn = '原密码不正确'
                        return render(request, 'home/user_central.html', locals())
                    else:
                        message_success = '密码修改成功'
                        current_user = models.User.objects.get(user_id=request.session.get('user_id', None))
                        current_user.user_psw = new_psw
                        current_user.save()
                        return render(request, 'home/user_central.html', locals())
            elif real_name:
                # 设置姓名操作
                if real_name == '':
                    message_warn = '姓名不能为空'
                    return render(request, 'home/user_central.html', locals())
                else:
                    message_success = '姓名设置成功!'
                    current_user = models.User.objects.get(user_id=request.session.get('user_id', None))
                    current_user.user_real_name = real_name
                    current_user.save()
                    return render(request, 'home/user_central.html', locals())
        else:
            return render(request, 'home/user_central.html', locals())
    return render(request, 'home/user_central.html', locals())


# 网页内容
class WebInfo:
    def __init__(self, theme):
        self.action_history = models.ActionHistory.objects.filter(action_theme=theme)
        self.content_item = ContentItem.objects.filter(item_theme=theme)
        self.discuss_list = models.Disscuss.objects.filter(discuss_theme=theme)
        self.editor_list = models.User.objects.filter(is_contribute="yes")
        self.latest_history = models.ActionHistory.objects.order_by('-action_date')[:5]


# 获取网页内容
def getinfo(theme):
    return WebInfo(theme)


# 历史页视图
def home_history(request):
    info = getinfo('家乡历史')
    user_content_item = None
    if request.session.get('is_login', None):
        user_content_item = models.ContentItem.objects.filter(
            item_editor_id=request.session['user_id'], item_theme='家乡历史')
    count_item = CountItem.objects.get(count_key='home')
    content_form = forms.ContentForm()
    discuss_form = forms.DiscussForm()
    message_success = "None"
    message_warn = 'None'
    if request.method == 'POST':
        # 获取表单
        content_form = forms.ContentForm(request.POST)
        discuss_form = forms.DiscussForm(request.POST)

        # 删除内容操作
        if user_content_item:
            message_delete_item = 'None'
            for foo in user_content_item:
                if request.POST.get('delete_contentCheckbox_' + foo.item_title):
                    delete_item = models.ContentItem.objects.get(
                        item_title=request.POST.get('delete_contentCheckbox_' + foo.item_title))
                    new_action_history = models.ActionHistory()
                    new_action_history.action_type = '删除'
                    new_action_history.action_starter = request.session.get('user_id', None)
                    new_action_history.action_target = foo.item_title
                    new_action_history.action_theme = '家乡历史'
                    new_action_history.save()
                    delete_item.delete()
                    message_delete_item = '删除成功!'

        # 添加内容操作
        if content_form.is_valid():
            content = content_form.cleaned_data.get('content')
            title = content_form.cleaned_data.get('titleItem')
            same_title = models.ContentItem.objects.filter(item_title=title)
            if same_title:
                message_warn = '标题相同, 请确认你编辑的内容'
                # return redirect('/history/')
                return render(request, 'home/home_history.html', locals())
            else:
                new_content = models.ContentItem()
                new_content.item_theme = '家乡历史'
                new_content.item_title = title
                new_content.item_content = content
                new_content.item_editor_id = request.session.get('user_id', None)
                new_content.save()
                current_user = models.User.objects.get(user_id=request.session.get('user_id', None))
                current_user.is_contribute = 'yes'
                current_user.editor_times += 1
                current_user.save()
                new_action_history = models.ActionHistory()
                new_action_history.action_type = '添加'
                new_action_history.action_starter = request.session.get('user_id', None)
                new_action_history.action_target = title
                new_action_history.action_theme = '家乡历史'
                new_action_history.save()
                message_success = "内容提交成功!"
                count_item.item_num += 1
                count_item.save()
                # return redirect('/history/')
                return render(request, 'home/home_history.html', locals())

        # 添加讨论操作
        elif discuss_form.is_valid():
            discuss = discuss_form.cleaned_data.get('discuss')
            discuss_title = discuss_form.cleaned_data.get('discuss_title')
            same_discuss_title = models.ContentItem.objects.filter(item_title=discuss_title)
            if same_discuss_title:
                message_warn = '标题相同, 请确认你编辑的内容'
                return render(request, 'home/home_history.html', locals())
            else:
                new_discuss = models.Disscuss()
                new_discuss.discuss_theme = '家乡历史'
                new_discuss.discuss_title = discuss_title
                new_discuss.discuss_content = discuss
                new_discuss.discuss_commit_id = request.session.get('user_id', None)
                new_discuss.save()
                message_success = "内容提交成功!"
                current_user = models.User.objects.get(user_id=request.session.get('user_id', None))
                current_user.is_contribute = 'yes'
                current_user.discuss_num += 1
                current_user.save()
                count_item.discuss_num += 1
                count_item.save()
                return render(request, 'home/home_history.html', locals())
        else:
            return render(request, 'home/home_history.html', locals())
    return render(request, 'home/home_history.html', locals())


# 名人页视图
def home_star(request):
    count_item = CountItem.objects.get(count_key='home')
    content_item = ContentItem.objects.filter(item_theme='家乡名人')
    discuss_list = models.Disscuss.objects.filter(discuss_theme='家乡名人')
    action_history = models.ActionHistory.objects.filter(action_theme='家乡名人')
    user_content_item = None
    editor_list = models.User.objects.filter(is_contribute="yes")
    if request.session.get('is_login', None):
        user_content_item = models.ContentItem.objects.filter(
            item_editor_id=request.session['user_id'], item_theme='家乡名人')
    content_form = forms.ContentForm()
    discuss_form = forms.DiscussForm()
    message_success = "None"
    message_warn = 'None'
    if request.method == 'POST':
        content_form = forms.ContentForm(request.POST)
        discuss_form = forms.DiscussForm(request.POST)

        # 删除内容操作
        if user_content_item:
            message_delete_item = 'None'
            for foo in user_content_item:
                if request.POST.get('delete_contentCheckbox_' + foo.item_title):
                    delete_item = models.ContentItem.objects.get(
                        item_title=request.POST.get('delete_contentCheckbox_' + foo.item_title))
                    new_action_history = models.ActionHistory()
                    new_action_history.action_type = '删除'
                    new_action_history.action_starter = request.session.get('user_id', None)
                    new_action_history.action_target = foo.item_title
                    new_action_history.action_theme = '家乡名人'
                    new_action_history.save()
                    delete_item.delete()
                    message_delete_item = '删除成功!'

        if content_form.is_valid():
            content = content_form.cleaned_data.get('content')
            title = content_form.cleaned_data.get('titleItem')
            same_title = models.ContentItem.objects.filter(item_title=title)
            if same_title:
                message_warn = '标题相同, 请确认你编辑的内容'
                return render(request, 'home/home_star.html', locals())
            else:
                new_content = models.ContentItem()
                new_content.item_theme = '家乡名人'
                new_content.item_title = title
                new_content.item_content = content
                new_content.item_editor_id = request.session.get('user_id', None)
                new_content.save()
                new_action_history = models.ActionHistory()
                new_action_history.action_type = '添加'
                new_action_history.action_starter = request.session.get('user_id', None)
                new_action_history.action_target = title
                new_action_history.action_theme = '家乡名人'
                new_action_history.save()
                message_success = "内容提交成功!"
                count_item.item_num += 1
                count_item.save()
                return render(request, 'home/home_star.html', locals())
        elif discuss_form.is_valid():
            discuss = discuss_form.cleaned_data.get('discuss')
            discuss_title = discuss_form.cleaned_data.get('discuss_title')
            same_discuss_title = models.ContentItem.objects.filter(item_title=discuss_title)
            if same_discuss_title:
                message_warn = '标题相同, 请确认你编辑的内容'
                return render(request, 'home/home_star.html', locals())
            else:
                new_discuss = models.Disscuss()
                new_discuss.discuss_theme = '家乡名人'
                new_discuss.discuss_title = discuss_title
                new_discuss.discuss_content = discuss
                new_discuss.discuss_commit_id = request.session.get('user_id', None)
                new_discuss.save()
                message_success = "内容提交成功!"
                count_item.discuss_num += 1
                count_item.save()
                return render(request, 'home/home_star.html', locals())
        else:
            return render(request, 'home/home_star.html', locals())
    return render(request, 'home/home_star.html', locals())


# 美景页视图
def home_beauty(request):
    count_item = CountItem.objects.get(count_key='home')
    content_item = ContentItem.objects.filter(item_theme='家乡美景')
    discuss_list = models.Disscuss.objects.filter(discuss_theme='家乡美景')
    action_history = models.ActionHistory.objects.filter(action_theme='家乡美景')
    user_content_item = None
    if request.session.get('is_login', None):
        user_content_item = models.ContentItem.objects.filter(
            item_editor_id=request.session['user_id'], item_theme='家乡美景')
    content_form = forms.ContentForm()
    discuss_form = forms.DiscussForm()
    message_success = "None"
    message_warn = 'None'
    if request.method == 'POST':
        content_form = forms.ContentForm(request.POST)
        discuss_form = forms.DiscussForm(request.POST)

        # 删除内容操作
        if user_content_item:
            message_delete_item = 'None'
            for foo in user_content_item:
                if request.POST.get('delete_contentCheckbox_' + foo.item_title):
                    delete_item = models.ContentItem.objects.get(
                        item_title=request.POST.get('delete_contentCheckbox_' + foo.item_title))
                    new_action_history = models.ActionHistory()
                    new_action_history.action_type = '删除'
                    new_action_history.action_starter = request.session.get('user_id', None)
                    new_action_history.action_target = foo.item_title
                    new_action_history.action_theme = '家乡美景'
                    new_action_history.save()
                    delete_item.delete()
                    message_delete_item = '删除成功!'

        if content_form.is_valid():
            content = content_form.cleaned_data.get('content')
            title = content_form.cleaned_data.get('titleItem')
            same_title = models.ContentItem.objects.filter(item_title=title)
            if same_title:
                message_warn = '标题相同, 请确认你编辑的内容'
                return render(request, 'home/home_beauty.html', locals())
            else:
                new_content = models.ContentItem()
                new_content.item_theme = '家乡美景'
                new_content.item_title = title
                new_content.item_content = content
                new_content.item_editor_id = request.session.get('user_id', None)
                new_content.save()
                new_action_history = models.ActionHistory()
                new_action_history.action_type = '添加'
                new_action_history.action_starter = request.session.get('user_id', None)
                new_action_history.action_target = title
                new_action_history.action_theme = '家乡美景'
                new_action_history.save()
                message_success = "内容提交成功!"
                count_item.item_num += 1
                count_item.save()
                return render(request, 'home/home_beauty.html', locals())
        elif discuss_form.is_valid():
            discuss = discuss_form.cleaned_data.get('discuss')
            discuss_title = discuss_form.cleaned_data.get('discuss_title')
            same_discuss_title = models.ContentItem.objects.filter(item_title=discuss_title)
            if same_discuss_title:
                message_warn = '标题相同, 请确认你编辑的内容'
                return render(request, 'home/home_beauty.html', locals())
            else:
                new_discuss = models.Disscuss()
                new_discuss.discuss_theme = '家乡美景'
                new_discuss.discuss_title = discuss_title
                new_discuss.discuss_content = discuss
                new_discuss.discuss_commit_id = request.session.get('user_id', None)
                new_discuss.save()
                message_success = "内容提交成功!"
                count_item.discuss_num += 1
                count_item.save()
                return render(request, 'home/home_beauty.html', locals())
        else:
            return render(request, 'home/home_beauty.html', locals())
    return render(request, 'home/home_beauty.html', locals())


# 建筑页视图
def home_building(request):
    count_item = CountItem.objects.get(count_key='home')
    content_item = ContentItem.objects.filter(item_theme='家乡建筑')
    discuss_list = models.Disscuss.objects.filter(discuss_theme='家乡建筑')
    action_history = models.ActionHistory.objects.filter(action_theme='家乡建筑')
    user_content_item = None
    if request.session.get('is_login', None):
        user_content_item = models.ContentItem.objects.filter(
            item_editor_id=request.session['user_id'], item_theme='家乡建筑')
    content_form = forms.ContentForm()
    discuss_form = forms.DiscussForm()
    message_success = "None"
    message_warn = 'None'
    if request.method == 'POST':
        content_form = forms.ContentForm(request.POST)
        discuss_form = forms.DiscussForm(request.POST)

        # 删除内容操作
        if user_content_item:
            message_delete_item = 'None'
            for foo in user_content_item:
                if request.POST.get('delete_contentCheckbox_' + foo.item_title):
                    delete_item = models.ContentItem.objects.get(
                        item_title=request.POST.get('delete_contentCheckbox_' + foo.item_title))
                    new_action_history = models.ActionHistory()
                    new_action_history.action_type = '删除'
                    new_action_history.action_starter = request.session.get('user_id', None)
                    new_action_history.action_target = foo.item_title
                    new_action_history.action_theme = '家乡建筑'
                    new_action_history.save()
                    delete_item.delete()
                    message_delete_item = '删除成功!'

        if content_form.is_valid():
            content = content_form.cleaned_data.get('content')
            title = content_form.cleaned_data.get('titleItem')
            same_title = models.ContentItem.objects.filter(item_title=title)
            if same_title:
                message_warn = '标题相同, 请确认你编辑的内容'
                return render(request, 'home/home_building.html', locals())
            else:
                new_content = models.ContentItem()
                new_content.item_theme = '家乡建筑'
                new_content.item_title = title
                new_content.item_content = content
                new_content.item_editor_id = request.session.get('user_id', None)
                new_content.save()
                new_action_history = models.ActionHistory()
                new_action_history.action_type = '添加'
                new_action_history.action_starter = request.session.get('user_id', None)
                new_action_history.action_target = title
                new_action_history.action_theme = '家乡建筑'
                new_action_history.save()
                message_success = "内容提交成功!"
                count_item.item_num += 1
                count_item.save()
                return render(request, 'home/home_building.html', locals())
        elif discuss_form.is_valid():
            discuss = discuss_form.cleaned_data.get('discuss')
            discuss_title = discuss_form.cleaned_data.get('discuss_title')
            same_discuss_title = models.ContentItem.objects.filter(item_title=discuss_title)
            if same_discuss_title:
                message_warn = '标题相同, 请确认你编辑的内容'
                return render(request, 'home/home_building.html', locals())
            else:
                new_discuss = models.Disscuss()
                new_discuss.discuss_theme = '家乡建筑'
                new_discuss.discuss_title = discuss_title
                new_discuss.discuss_content = discuss
                new_discuss.discuss_commit_id = request.session.get('user_id', None)
                new_discuss.save()
                message_success = "内容提交成功!"
                count_item.discuss_num += 1
                count_item.save()
                return render(request, 'home/home_building.html', locals())
        else:
            return render(request, 'home/home_building.html', locals())
    return render(request, 'home/home_building.html', locals())


# 风俗页视图
def home_custom(request):
    count_item = CountItem.objects.get(count_key='home')
    content_item = ContentItem.objects.filter(item_theme='家乡风俗')
    discuss_list = models.Disscuss.objects.filter(discuss_theme='家乡风俗')
    action_history = models.ActionHistory.objects.filter(action_theme='家乡风俗')
    user_content_item = None
    if request.session.get('is_login', None):
        user_content_item = models.ContentItem.objects.filter(
            item_editor_id=request.session['user_id'], item_theme='家乡风俗')
    content_form = forms.ContentForm()
    discuss_form = forms.DiscussForm()
    message_success = "None"
    message_warn = 'None'
    if request.method == 'POST':
        content_form = forms.ContentForm(request.POST)
        discuss_form = forms.DiscussForm(request.POST)

        # 删除内容操作
        if user_content_item:
            message_delete_item = 'None'
            for foo in user_content_item:
                if request.POST.get('delete_contentCheckbox_' + foo.item_title):
                    delete_item = models.ContentItem.objects.get(
                        item_title=request.POST.get('delete_contentCheckbox_' + foo.item_title))
                    new_action_history = models.ActionHistory()
                    new_action_history.action_type = '删除'
                    new_action_history.action_starter = request.session.get('user_id', None)
                    new_action_history.action_target = foo.item_title
                    new_action_history.action_theme = '家乡风俗'
                    new_action_history.save()
                    delete_item.delete()
                    message_delete_item = '删除成功!'

        if content_form.is_valid():
            content = content_form.cleaned_data.get('content')
            title = content_form.cleaned_data.get('titleItem')
            same_title = models.ContentItem.objects.filter(item_title=title)
            if same_title:
                message_warn = '标题相同, 请确认你编辑的内容'
                return render(request, 'home/home_custom.html', locals())
            else:
                new_content = models.ContentItem()
                new_content.item_theme = '家乡风俗'
                new_content.item_title = title
                new_content.item_content = content
                new_content.item_editor_id = request.session.get('user_id', None)
                new_content.save()
                new_action_history = models.ActionHistory()
                new_action_history.action_type = '添加'
                new_action_history.action_starter = request.session.get('user_id', None)
                new_action_history.action_target = title
                new_action_history.action_theme = '家乡风俗'
                new_action_history.save()
                message_success = "内容提交成功!"
                count_item.item_num += 1
                count_item.save()
                return render(request, 'home/home_custom.html', locals())
        elif discuss_form.is_valid():
            discuss = discuss_form.cleaned_data.get('discuss')
            discuss_title = discuss_form.cleaned_data.get('discuss_title')
            same_discuss_title = models.ContentItem.objects.filter(item_title=discuss_title)
            if same_discuss_title:
                message_warn = '标题相同, 请确认你编辑的内容'
                return render(request, 'home/home_custom.html', locals())
            else:
                new_discuss = models.Disscuss()
                new_discuss.discuss_theme = '家乡风俗'
                new_discuss.discuss_title = discuss_title
                new_discuss.discuss_content = discuss
                new_discuss.discuss_commit_id = request.session.get('user_id', None)
                new_discuss.save()
                message_success = "内容提交成功!"
                count_item.discuss_num += 1
                count_item.save()
                return render(request, 'home/home_custom.html', locals())
        else:
            return render(request, 'home/home_custom.html', locals())
    return render(request, 'home/home_custom.html', locals())
